﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WMM.Tapioca.Instance;
using WMM.Tapioca.Taxonomy;
using WMM.Tapioca.Linkbase;

namespace WMM.Tapioca.Formula.Filters
{
    /// <summary>
    /// The instant-duration filter can be used to match facts that are reported as at an instant where
    /// that instant matches the start or end of the duration for which another fact has been reported.
    /// </summary>
    public class InstantDurationFilter : Filter
    {
        private string variable;

        /// <returns> Dimension. </returns>
         public string Variable
        {
            get { return variable; }
            set { variable = value; }
        }

        private string boundary;

        /// <returns> Dimension. </returns>
        public string Boundary
        {
            get { return boundary; }
            set { boundary = value; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public InstantDurationFilter(Resource resource)
            : base(resource)
        {
            Label = resource.Label;

            variable = (string)resource.ResourceXElement.Attribute("variable") ?? string.Empty;

            boundary = (string)resource.ResourceXElement.Attribute("boundary") ?? string.Empty;
        }


        public override List<FactItem> EvaluateFilter(VariableSet variableSet, List<FactItem> itemsToFilter, DTS dts)
        {
            List<FactItem> itemListTemp = new List<FactItem>();

            DateTime date = DateTime.Now; ;

            List<FactItem> factItems = variableSet.variableItems[Variable];

            foreach (FactItem itemToFilter in itemsToFilter)
            {
                foreach (FactItem item in factItems)
                {
                    if (item.ContextRef.IsDurationPeriod)
                    {
                        if (Boundary == "start")
                        {
                            date = item.ContextRef.PeriodStartDate.AddDays(-1);
                        }
                        else
                        {
                            date = item.ContextRef.PeriodEndDate;
                        }
                    }

                    if (Complement ? !(itemToFilter.ContextRef.IsInstantPeriod && itemToFilter.ContextRef.InstantDate.Equals(date)) :
                        itemToFilter.ContextRef.IsInstantPeriod && itemToFilter.ContextRef.InstantDate.Equals(date))
                    {
                        itemListTemp.Add(itemToFilter);
                        break;
                    }
                }
            }            

            return itemListTemp;
        }
    }
}
